<?php

namespace App\Model;

use App\Model\ShopAttrValModel;
use Illuminate\Database\Eloquent\Model;

class SkuModel extends Model
{
	//定义一个表名
	protected $table = 'shop_good_sku';
	//定义主键
	protected $primaryKey = 'id';

	public function getPropertyAttribute(){
		$property_id = $this->attributes['property_id'];

		$string=rtrim($property_id,",");//删除右边多余的逗号
		$str=explode(",",$string);
		$property = "";
		foreach ($str as $vv) {
			$av=explode("-",$vv);
			$vname=ShopAttrValModel::where('id',$av[1])->value('vname');
			$property .= $vname.",";
		}
		return $property;
	}

	function getSnameAttribute(){
		$name = AddShop::where('id',$this->store_id)->value('name');
		return $name;
	}

	//sku加销量
	public static function min($sku_id,$num)
	{
		if($num<0){
			throw new \Exception(retStrInfo(202));//数据错误
		}
		//加销量
		self::where('id',$sku_id)->increment('sale_num',$num);

		$store_sum = StoreGoodModel::where('gid',$sku_id)->sum('num');
		if($num - $store_sum > 0){
			$due_num = $num - $store_sum;
			//减库存
			self::where('id',$sku_id)->decrement('sum',$due_num);
		}

		//减库存
		self::where('id',$sku_id)->decrement('sum',$num);
	}

	//查询销售价
	function getSpriceAttribute(){
		$price = AddShop::where('id',$this->store_id)->value('new_sell_price');
		return $price;
	}

	function getMstateAttribute(){
		$state = ShopGoodModel::where('id',$this->gid)->value('state');
		$arr = ['1'=>'上架','2'=>'下架','3'=>'已删除'];
		return $arr[$state];
	}
}
